package com.example.my.meila.api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by zhangwei on 16/10/27.
 * Okhttp
 * Gson
 */
public class RetroManager {
    private static volatile RetroManager instance = null;
    private static Retrofit retrofit;
    OkHttpClient client;
    private static final int DEFAULT_READ_TIMEOUT = 15 * 1000;
    private static final int DEFAULT_CONNECT_TIMEOUT = 15 * 1000;
    private static final int DEFAULT_WRITE_TIMEOUT = 15 * 1000;


    private RetroManager() {
        initOkhttpClient();
        initRetrofit();

    }

    public static RetroManager getInstance() {
        if (instance == null) {
            synchronized (RetroManager.class) {
                if (instance == null) {
                    instance = new RetroManager();
                }
            }
        }
        return instance;
    }

    /**
     *
     */
    public void initRetrofit() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(client)
                    .baseUrl(ApiService.BASE_URL)
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(getGson()))
                    .build();
        }

    }

    private void initOkhttpClient() {
        if (client == null) {
            client = new OkHttpClient.Builder()
                    .readTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.MILLISECONDS)
                    .connectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                    .writeTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
                    .build();
        }
    }

    /**
     * @return
     */
    public Gson getGson() {
        return new GsonBuilder()
                .serializeNulls()
//                .setDateFormat("yyyy-MM-dd")//设置日期格式
                .create();
    }

    public ApiService getApiService() {
        return retrofit.create(ApiService.class);
    }

    public ApiRank getApiRank() {
        return retrofit.create(ApiRank.class);
    }


}